<?php

namespace App\Services\Cookie;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Cookie;

class Carts
{
    protected $request;

    const CART_NAME = 'carts_data_arr';

    protected $api_url = [
        'sku_index' => ['get', 'skus'],
        'carts_index' => ['get', 'buyer/carts'],
        'index' => ['post', 'carts/carts'],
        'carts_delete' => ['delete', 'buyer/carts'],
        'fresh_get' => ['post', 'buyer/carts/fresh_get'],
    ];

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * 获取购物车列表
     * @return array|mixed
     */
    public function getList()
    {
        $carts = $this->getData();
        return $carts;
    }

    public function getGlobalData()
    {
        //获取cookie中的cart_id
        $carts = $this->getData();

        //获取缓存中的数据
        $cache_key = 'carts_list:' . session('user_id');
        $cache_cart_list = Cache::get($cache_key);

        $data = [];
        if (session('user_id')) { //已登录状态直接获取线上购物车
            $cart_ids = array_column($carts, 'id');
            $cache_cart_ids = array_get($cache_cart_list, 'cart_ids');
            //如果缓存不存在或有差集就读取接口
            if ((!$cache_cart_ids || array_diff($cart_ids, $cache_cart_ids) || array_diff($cache_cart_ids, $cart_ids))) {
                //获取数据库数据
                $ret = http_web($this->api_url['carts_index'])->send(['type' => 'all', 'with' => 'product;sku']);
                if ($ret['code'] == 0) {
                    $cart_list['cart_ids'] = array_column($ret['data'], 'id');
                    $cart_list['data'] = $ret['data'];
                    $cart_list['count'] = count($cart_list['cart_ids']);
                    Cache::put($cache_key, $cart_list, 60);
                    $data = $cart_list;
                }
            } else {
                $data = $cache_cart_list;
            }
        } else {  //未登陆状态下从cookie获取sku id列表，并从数据库获取sku数据
            //从cookie中获取cookie，如果无sku，则返回空
            $sku_ids = array_column($carts, 'sku_id');
            if (!$sku_ids) {
                return [];
            }
            //获取缓存中的sku，并与cookie中的sku比对，如果一样，则通过缓存获取，如果存在差集则从数据库获取
            $cache_sku_ids = array_get($cache_cart_list, 'sku_ids');
            if ((!$cache_sku_ids || array_diff($sku_ids, $cache_sku_ids) || array_diff($cache_sku_ids, $sku_ids))) {
                $params = [
                    'search' => search_params(['id' => $sku_ids]),
                    'type' => 'all',
                    'with' => 'product'
                ];
                $ret = http_web($this->api_url['sku_index'])->send($params);
                if ($ret['code'] == 0) {
                    $sku_list['sku_ids'] = array_column($ret['data'], 'id');
                    $cart_list['count'] = count($sku_list['sku_ids']);
                    array_walk($carts, function (&$value, $key) use ($ret) {
                        foreach ($ret['data'] as $sku) {
                            if ($sku['id'] == $value['sku_id']) {
                                $value['product'] = $sku['product'];
                                unset($sku['product']);
                                $value['sku'] = $sku;
                            }
                        }
                    });
                    $cart_list['data'] = $carts;
                    Cache::put($cache_key, $cart_list, 60);
                    $data = $cart_list;
                }
            } else {
                $data = $cache_cart_list;
            }
        }

        return $data ? $data : [];
    }

    /**
     * 重置购物车
     * @param array $items
     */
    public function fresh($items = [])
    {
        Cookie::queue(self::CART_NAME, null, -1); // 销毁
    }

    /**
     * 重置购物车 并重新获取数据库存入cookie
     * @param array $items
     */
    public function fresh_get($items = [])
    {
        Cookie::queue(self::CART_NAME, null, -1); // 销毁
        $ret = http_web($this->api_url['fresh_get'])->send();
        $carts_data_arr=serialize($ret['data']);
        Cookie::queue(self::CART_NAME, $carts_data_arr);
        return $carts_data_arr;

    }

    /**
     * 添加单条数据
     * @param array $item
     */
    public function create($data = [], $cookie_data = [], $user = '')
    {
        //@todo 添加cookie
        /**
         * post 数据如下规则
         * 需要的数据有：shop_id,poduct_id,sku_id,num,type
         */
        if (!isset($data['status'])) {
            $data['status'] = 1;
        }
        if (!empty($user)) {
            $data['user_id'] = $user;
        }
        //请求部分
        $carts_product = [];
        if (!empty($cookie_data)) {
            $carts_data_arr = $cookie_data;
            $carts_product = array_unique(array_column($carts_data_arr, 'sku_id'));
            if (in_array($data['sku_id'], $carts_product)) {
                foreach ($carts_data_arr as $k => $v) {
                    if ($v['sku_id'] == $data['sku_id']) {
                        $carts_data_arr[$k]['num'] += $data['num'];
                    }
                }
            } else {
//
                    $carts_data_arr[] = $data;
            }
        } else {
            $carts_product[] = $data['sku_id'];

            //存储cart cookie
            $carts_data_arr = [];
            $carts_data_arr[] = $data;
        }
        //查询cookie相关产品信息

        $carts_data_arr = serialize($carts_data_arr);
        Cookie::queue(self::CART_NAME, $carts_data_arr);
        return $carts_data_arr;

    }

    /**
     * 清空购物车
     */
    public function allDestroy()
    {
        //@todo 清空所有商品
        if (session('user_id')) { //已登录-清空数据库购物车
            $ret = http_web($this->api_url['carts_delete'])->send(['type' => 'all']);
        }
        Cookie::queue(self::CART_NAME, null, -1); // 销毁
        return true;
    }

    /**
     * 批量删除购物车
     * @param array $cart_ids
     */
    public function batchDestroy($cart_ids = [], $sku_ids = [])
    {
        //@todo 根据条件清空部分商品
        if (session('user_id') && $cart_ids) {//登录状态下
            $params = [
                'type' => 'batch',
                'cart_ids' => $cart_ids
            ];
            $ret = http_web($this->api_url['carts_delete'])->send($params);
            $carts_data_arr = $ret['data'];
        } else {//未登录状态
            if(!$sku_ids){
                return true;
            }
            $carts = $this->getData();
            $carts_data_arr = array_filter($carts, function($cart) use($sku_ids){
                if(in_array($cart['sku_id'], $sku_ids)){
                    return false;
                }
                return $cart;
            });
        }

        Cookie::queue('carts_data_arr', serialize($carts_data_arr));
        return true;
    }

    private function getData()
    {
        $cart = $this->request->cookie(self::CART_NAME);
        $carts_data_arr = $cart ? unserialize($cart) : [];
        return $carts_data_arr;
    }



}